/*
 * COPYRIGHT:	2010 Christopher Smith, licenced under the GNU GPL v2; see COPYING in the top level directory
 * PROJECT:		sdedit
 * FILE:		toplabelctl.cpp
 * PURPOSE:		implementation of the "top labels" control used by the acl editor
 *				
 */

namespace TopLabel
{

PWSTR ClassName = L"SdEdTopLabels";

ATOM ClassAtom;

XFORM CommonTransform;

struct WindowClassLifetime;

class WindowObject : public ClassedWindowBase
{
	LISTBOX_CTRL *Columns;
	HFONT Font;

public:
	WindowObject(HWND parent, LISTBOX_CTRL *Columns, HFONT Font) :
		Columns(Columns),
		Font(Font)
	{
		Create(0, ClassName, L"Labels", WS_CHILD | WS_VISIBLE, 200, 0, 200, 100, parent, NULL, NULL, NULL);
	}

private:
	void ResizeWindow(int x, int y)
	{
		HDC Dc = GetDCEx(Wnd, NULL, DCX_NORESETATTRS | DCX_CLIPSIBLINGS);
		XFORM LocalTransform = CommonTransform;

		LocalTransform.eDx = 0;
		LocalTransform.eDy = (float)y;

		RaiseOnWin32ErrorT(Dc != NULL);
		RaiseOnWin32ErrorT(SetGraphicsMode(Dc, GM_ADVANCED));
		RaiseOnWin32ErrorT(SetWorldTransform(Dc, &LocalTransform));

		SelectObject(Dc, Font);
		SetBkMode(Dc, TRANSPARENT);

		RaiseOnWin32ErrorT(ReleaseDC(Wnd, Dc));
	}

	void Paint()
	{
		PAINTSTRUCT PaintStruct;
		HDC Dc = BeginPaint(Wnd, &PaintStruct);
		
		RaiseOnWin32ErrorT(Dc);

		for(UCHAR i = 0; i <= COL_MAX_ACE; i++)
			if(Columns[i].OverheadLabel && Columns[i].LabelX != -1)
				TextOut(Dc, 2, Columns[i].LabelX, Columns[i].OverheadLabel, (int)wcslen(Columns[i].OverheadLabel));

		EndPaint(Wnd, &PaintStruct);
	}

	virtual LRESULT RecieveMessage(HWND wnd, UINT msg, WPARAM wparam, LPARAM lparam) override
	{
		switch(msg)
		{
		case WM_SIZE:
			ResizeWindow(LOWORD(lparam), HIWORD(lparam));
			break;

		case WM_PAINT:
			Paint();
			break;
		}

		return ClassedWindowBase::RecieveMessage(wnd, msg, wparam, lparam);
	}

	friend WindowClassLifetime;
};

struct WindowClassLifetime
{
	WindowClassLifetime()
	{
		CommonTransform.eM11 = cosf((float)-M_PI_2);
		CommonTransform.eM12 = sinf((float)-M_PI_2);
		CommonTransform.eM21 = -sinf((float)-M_PI_2);
		CommonTransform.eM22 = cosf((float)-M_PI_2);

		WNDCLASS Class;
		RtlZeroStruct(Class);

		Class.hInstance = SdEditGModule;
		Class.hCursor = LoadCursor(NULL, IDC_ARROW);
		Class.lpfnWndProc = &ClassedWindowBase::ClassedWndProc;
		Class.hbrBackground = GetSysColorBrush(COLOR_BTNFACE);
		Class.lpszClassName = ClassName;
		Class.style = CS_OWNDC;

		ClassAtom = RegisterClass(&Class);

		RaiseOnWin32ErrorT(ClassAtom);
	}

	~WindowClassLifetime()
	{
		UnregisterClass(ClassName, SdEditGModule);
	}
};

}//namespace TopLabel